import requests
import json
import psutil

from com.atzl.common.UsersMessage import MessagesUsers

# 获取用户IP,MAC,正式地址
class GetSite:

    def get_site(self):
        try:
            dic = psutil.net_if_addrs()
            for adapter in dic:
                if adapter == 'WLAN' or adapter == '以太网':
                    snicList = dic[adapter]
                    for snic in snicList:
                        if snic.family.name in {'AF_LINK', 'AF_PACKET'}:
                            if adapter == 'WLAN':
                                MessagesUsers.WLAN_MAC = snic.address
                            else:
                                MessagesUsers.LAN_MAC = snic.address
                        elif snic.family.name == 'AF_INET':
                            if adapter == 'WLAN':
                                MessagesUsers.WLAN_IPv4 = snic.address
                            else:
                                MessagesUsers.LAN_IPv4 = snic.address

            ip = requests.get('https://checkip.amazonaws.com').text.strip()
            # print(ip)
            # 发送get请求
            url = f'http://ip-api.com/json/{ip}?fields=country,regionName,city,query&lang=zh-CN'
            # 其中fields字段为定义接受返回参数，可不传；lang为设置语言，zh-CN为中文，可以传
            res = requests.get(url)        # 发送请求
            data = json.loads(res.text)
            country = data.get("country")
            state = data.get("regionName")
            city = data.get("city")
            MessagesUsers.INTERNET_IP = ip
            MessagesUsers.PLACE_NATION = country
            MessagesUsers.PLACE_STATE = state
            MessagesUsers.PLACE_CITY = city
        except Exception:
            MessagesUsers.INTERNET_IP = '未连公网'
            MessagesUsers.PLACE_NATION = '未连公网'
            MessagesUsers.PLACE_STATE = '未连公网'
            MessagesUsers.PLACE_CITY = '未连公网'
            MessagesUsers.WLAN_MAC = '没有无线网物理地址'
            MessagesUsers.LAN_MAC = '没有以太网物理地址'